package com.atguigu.srb.sms.controller.api;

import com.atguigu.common.exception.Assert;
import com.atguigu.common.result.R;
import com.atguigu.common.result.ResponseEnum;
import com.atguigu.common.util.RandomUtils;
import com.atguigu.common.util.RegexValidateUtils;
import com.atguigu.ronglianyun.sms.service.SmsService;
import com.atguigu.srb.sms.client.CoreUserinfoClient;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.concurrent.TimeUnit;

@RestController
@Api("短信管理")
//@CrossOrigin
@Slf4j
@RequestMapping("/api/sms")
public class ApiSmsController {

    private final SmsService smsService;
    private final RedisTemplate<String ,Object> redisTemplate;
    private final CoreUserinfoClient coreUserinfoClient;

    public ApiSmsController(SmsService smsService, RedisTemplate<String, Object> redisTemplate, CoreUserinfoClient coreUserinfoClient) {
        this.smsService = smsService;
        this.redisTemplate = redisTemplate;
        this.coreUserinfoClient = coreUserinfoClient;
    }

    @GetMapping("/send/{mobile}")
    @ApiOperation("获取验证码")
    public R send(@ApiParam(value = "手机号", required = true) @PathVariable String mobile) {
        // 校验手机号不能为空
        Assert.notEmpty(mobile, ResponseEnum.MOBILE_NULL_ERROR);

        // 校验手机号格式正确
        Assert.isTrue(RegexValidateUtils.checkCellphone(mobile), ResponseEnum.MOBILE_ERROR);

        // 验证手机号是否被注册
        boolean exists = coreUserinfoClient.checkMobile(mobile);
        Assert.isTrue(!exists, ResponseEnum.MOBILE_EXIST_ERROR);


        // 发送短信业务
        String[] datas = new String[2];
        datas[0] = RandomUtils.getFourBitRandom();
        datas[1] = "5";
//        smsService.send(mobile, SmsProperties.TEMPLATE_CODE, datas);

        // 将验证码存入redis
        redisTemplate.opsForValue().set("srb:sms:code:" + mobile, datas[0], 5, TimeUnit.MINUTES);

        return R.ok().message("短信发送成功");
    }
}
